import { useTrack } from '@/hooks'
import { useTreeStore } from '@/store/tree'
// import { useTtsaStore } from '@/store/ttsa';

export default function useBranch(props, emit) {
  const tree = useTreeStore();
  const delayTime = computed(() => {
    if (!tree?.current || tree?.current?.duration <= 17) {
      return 0;
    }
    return tree?.current?.duration - 17;
  });
  const loadingTime = computed(() => {
    if (!tree?.current || tree?.current?.duration <= 17) {
      return tree?.current?.duration;
    }
    return 17;
  });
  let delayTimer = null;
  let loadingTimer = null;
  const loadingValue = ref(0)  // let show = false;
  const closeBranch = () => emit('unmount');

  const handClick = (node) => {
    const { setTrack } = useTrack();
    if (props.type === 'ask') {
      // 问答互动上报统计
      setTrack({ name: 'interactive', type: 'ask' });
    } else {
      // 卡片引导点击统计
      setTrack({ name: 'interactive', type: 'click' });
    };
    props.handEvent(node);
    closeBranch();
  }

  const loadingLoop = () => {
    loadingValue.value = loadingTime.value;
    loadingTimer = setInterval(() => {
      loadingValue.value -= 1;
      if (loadingValue.value <= 0) {
        closeBranch();
      }
    }, 1000);
  };


  const init = () => {
    // show = true;
    if (loadingTime.value && props.type !== 'ask') {
      loadingLoop();
    };
  };

  const start = () => {
    if (delayTime.value && props.type !== 'ask') {
      delayTimer = setTimeout(init, delayTime.value * 1000);
    } else {
      init();
      // delayTimer = setTimeout(init, delayTime.value * 1000);
    }
  }

  const destroy = () => {
    if (loadingTimer) {
      clearInterval(loadingTimer);
      loadingTimer = null;
      loadingValue.value = 0;
    }
    if (delayTimer) {
      clearTimeout(delayTimer);
      delayTimer = null;
    }
  }

  onMounted(() => {
    start()
  });

  onBeforeUnmount(() => {
    destroy()
  })

  return {
    handClick,
    start,
    destroy,
    loadingValue
  }
}